<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { message, Modal } from 'ant-design-vue';
import dayjs from 'dayjs';

// 接口定义
interface Pet {
  id: string;
  name: string;
  type: string;
  age?: number;
  breed?: string;
  ownerName: string;
  contact: string;
}

interface Doctor {
  id: string;
  name: string;
  department: string;
  available: boolean;
}

interface RegistrationRecord {
  id: string;
  registrationTime: string;
  petName: string;
  ownerName: string;
  category: string;
  categoryName: string;
  doctorName: string;
  registrationFee: number;
}

// 响应式数据
const searchQuery = ref('');
const selectedPet = ref<null | Pet>(null);
const registrationForm = ref({
  category: '',
  doctor: '',
});

const historyFilter = ref({
  status: 'all',
  dateRange: [dayjs().startOf('day'), dayjs().endOf('day')],
  search: '',
});

// 模拟数据
const pets = ref<Pet[]>([]);
const doctors = ref<Doctor[]>([]);
const registrationHistory = ref<RegistrationRecord[]>([]);

// 表格列定义
const historyColumns = [
  {
    title: '挂号时间',
    dataIndex: 'registrationTime',
    key: 'registrationTime',
  },
  {
    title: '挂号宠物',
    dataIndex: 'petName',
    key: 'petName',
  },
  {
    title: '主人',
    dataIndex: 'ownerName',
    key: 'ownerName',
  },
  {
    title: '挂号分类',
    dataIndex: 'category',
    key: 'category',
  },
  {
    title: '挂号类别',
    dataIndex: 'categoryName',
    key: 'categoryName',
  },
  {
    title: '主治医生',
    dataIndex: 'doctorName',
    key: 'doctorName',
  },
  {
    title: '挂号费',
    dataIndex: 'registrationFee',
    key: 'registrationFee',
  },
  {
    title: '删除',
    key: 'action',
    width: 80,
  },
];

// 计算属性
const filteredPets = computed(() => {
  if (!searchQuery.value) return pets.value;

  return pets.value.filter(
    (pet) =>
      pet.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      pet.ownerName.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      pet.contact.includes(searchQuery.value),
  );
});

const availableDoctors = computed(() => {
  return doctors.value.filter((doctor) => doctor.available);
});

const canSubmit = computed(() => {
  return (
    selectedPet.value &&
    registrationForm.value.category &&
    registrationForm.value.doctor
  );
});

const filteredHistory = computed(() => {
  let result = registrationHistory.value;

  // 按状态筛选
  if (historyFilter.value.status !== 'all') {
    // 这里可以根据实际需求添加状态筛选逻辑
  }

  // 按搜索关键词筛选
  if (historyFilter.value.search) {
    const search = historyFilter.value.search.toLowerCase();
    result = result.filter(
      (record) =>
        record.petName.toLowerCase().includes(search) ||
        record.ownerName.toLowerCase().includes(search) ||
        record.doctorName.toLowerCase().includes(search),
    );
  }

  return result;
});

const todayRegistrations = computed(() => {
  const today = dayjs().format('YYYY-MM-DD');
  return registrationHistory.value.filter((record) =>
    record.registrationTime.startsWith(today),
  ).length;
});

const pendingRegistrations = computed(() => {
  return registrationHistory.value.filter((record) =>
    record.registrationTime.startsWith(dayjs().format('YYYY-MM-DD')),
  ).length;
});

const completedRegistrations = computed(() => {
  return registrationHistory.value.length;
});

// 方法
const searchPets = () => {
  // 搜索逻辑已在计算属性中实现
};

const selectPet = (pet: Pet) => {
  selectedPet.value = pet;
};

const onCategoryChange = () => {
  registrationForm.value.doctor = '';
};

const submitRegistration = () => {
  if (!selectedPet.value) {
    message.warning('请先选择宠物');
    return;
  }

  if (!registrationForm.value.category) {
    message.warning('请选择挂号类别');
    return;
  }

  if (!registrationForm.value.doctor) {
    message.warning('请选择医生');
    return;
  }

  const selectedDoctor = doctors.value.find(
    (d) => d.id === registrationForm.value.doctor,
  );
  const categoryNames = {
    wechat: '微信挂号',
    phone: '电话挂号',
    walkin: '现场挂号',
    emergency: '急诊挂号',
  };

  // 创建新的挂号记录
  const newRecord: RegistrationRecord = {
    id: `R${Date.now()}`,
    registrationTime: dayjs().format('YYYY-MM-DD'),
    petName: selectedPet.value.name,
    ownerName: selectedPet.value.ownerName,
    category: '挂号服务',
    categoryName:
      categoryNames[
        registrationForm.value.category as keyof typeof categoryNames
      ],
    doctorName: selectedDoctor?.name || '',
    registrationFee: 20,
  };

  registrationHistory.value.unshift(newRecord);

  message.success('挂号成功！');

  // 重置表单
  registrationForm.value = {
    category: '',
    doctor: '',
  };
  selectedPet.value = null;
};

const onDateRangeChange = () => {
  // 日期范围变化处理
};

const setDateRange = (range: string) => {
  const today = dayjs();
  switch (range) {
    case '-7': {
      historyFilter.value.dateRange = [today.subtract(7, 'day'), today];
      break;
    }
    case '-3': {
      historyFilter.value.dateRange = [today.subtract(3, 'day'), today];
      break;
    }
    case 'today': {
      historyFilter.value.dateRange = [
        today.startOf('day'),
        today.endOf('day'),
      ];
      break;
    }
  }
};

const searchHistory = () => {
  // 搜索逻辑已在计算属性中实现
};

const deleteRegistration = (record: RegistrationRecord) => {
  Modal.confirm({
    title: '删除挂号记录',
    content: `确定要删除 ${record.petName} 的挂号记录吗？`,
    okType: 'danger',
    onOk: () => {
      const index = registrationHistory.value.findIndex(
        (r) => r.id === record.id,
      );
      if (index !== -1) {
        registrationHistory.value.splice(index, 1);
        message.success('挂号记录已删除');
      }
    },
  });
};

const showQuickRegistration = () => {
  message.info('快速挂号功能');
};

const showCustomerSearch = () => {
  message.info('查找顾客功能');
};

const showDoctorSchedule = () => {
  message.info('医生排班功能');
};

const showStatistics = () => {
  message.info('挂号统计功能');
};

// 初始化数据
onMounted(() => {
  // 模拟宠物数据
  pets.value = [
    {
      id: 'P001',
      name: '球球',
      type: '狗类',
      age: 3,
      breed: '金毛',
      ownerName: '赵女士',
      contact: '18300138001',
    },
    {
      id: 'P002',
      name: '兜兜',
      type: '猫类',
      age: 2,
      breed: '英短',
      ownerName: '王先生',
      contact: '18243535',
    },
  ];

  // 模拟医生数据
  doctors.value = [
    {
      id: 'D001',
      name: '曾前台',
      department: '前台',
      available: true,
    },
    {
      id: 'D002',
      name: '李医生',
      department: '内科',
      available: true,
    },
    {
      id: 'D003',
      name: '张医生',
      department: '外科',
      available: false,
    },
  ];

  // 模拟历史挂号记录
  registrationHistory.value = [
    {
      id: 'R001',
      registrationTime: '2019-08-07',
      petName: '球球',
      ownerName: '赵女士',
      category: '挂号服务',
      categoryName: '微信挂号',
      doctorName: '曾前台',
      registrationFee: 20,
    },
  ];
});
</script>

<template>
  <div class="registration-page">
    <div class="page-container">
      <!-- 左侧：选择宠物 -->
      <div class="pet-selection-panel">
        <div class="panel-header">
          <h3>🐾 选择宠物</h3>
        </div>

        <div class="search-section">
          <a-input
            v-model:value="searchQuery"
            placeholder="顾客名/宠物名/手机号"
            @keyup.enter="searchPets"
            @change="searchPets"
          >
            <template #suffix>
              <a-button type="text" @click="searchPets">🔍</a-button>
            </template>
          </a-input>
        </div>

        <div class="pet-list">
          <div
            v-for="pet in filteredPets"
            :key="pet.id"
            class="pet-item"
            :class="{ active: selectedPet?.id === pet.id }"
            @click="selectPet(pet)"
          >
            <div class="pet-avatar">
              <a-avatar :size="40">
                {{ pet.ownerName.charAt(0) }}
              </a-avatar>
            </div>
            <div class="pet-info">
              <div class="pet-name">{{ pet.name }}({{ pet.ownerName }})</div>
              <div class="pet-contact">{{ pet.contact }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间：挂号表单和历史记录 -->
      <div class="registration-content">
        <!-- 本次挂号宠物 -->
        <div class="current-pet-section" v-if="selectedPet">
          <a-card title="本次挂号宠物" class="current-pet-card">
            <div class="pet-details">
              <div class="pet-icon">🦴</div>
              <div class="pet-info-grid">
                <div class="info-row">
                  <span class="label">宠物姓名:</span>
                  <span class="value">{{ selectedPet.name }}</span>
                </div>
                <div class="info-row">
                  <span class="label">宠物种类:</span>
                  <span class="value">{{ selectedPet.type }}</span>
                </div>
                <div class="info-row">
                  <span class="label">年龄:</span>
                  <span class="value">{{ selectedPet.age || '未填写' }}</span>
                </div>
                <div class="info-row">
                  <span class="label">宠物品种:</span>
                  <span class="value">{{ selectedPet.breed || '未填写' }}</span>
                </div>
                <div class="info-row">
                  <span class="label">主人姓名:</span>
                  <span class="value">{{ selectedPet.ownerName }}</span>
                </div>
                <div class="info-row">
                  <span class="label">联系方式:</span>
                  <span class="value">{{ selectedPet.contact }}</span>
                </div>
              </div>
            </div>
          </a-card>
        </div>

        <!-- 挂号详情 -->
        <div class="registration-form-section">
          <a-card title="挂号详情" class="registration-form-card">
            <a-form :model="registrationForm" layout="vertical">
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="挂号类别" required>
                    <a-select
                      v-model:value="registrationForm.category"
                      placeholder="选择挂号类别及医生"
                      @change="onCategoryChange"
                    >
                      <a-select-option value="wechat">微信挂号</a-select-option>
                      <a-select-option value="phone">电话挂号</a-select-option>
                      <a-select-option value="walkin">现场挂号</a-select-option>
                      <a-select-option value="emergency">
                        急诊挂号
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="医生" required>
                    <a-select
                      v-model:value="registrationForm.doctor"
                      placeholder="选择挂号类别及医生"
                      :disabled="!registrationForm.category"
                    >
                      <a-select-option
                        v-for="doctor in availableDoctors"
                        :key="doctor.id"
                        :value="doctor.id"
                      >
                        {{ doctor.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>

              <div class="submit-section">
                <a-button
                  type="primary"
                  size="large"
                  :disabled="!canSubmit"
                  @click="submitRegistration"
                >
                  提交挂号单
                </a-button>
              </div>
            </a-form>
          </a-card>
        </div>

        <!-- 历史挂号记录 -->
        <div class="history-section">
          <a-card title="历史挂号记录显示" class="history-card">
            <!-- 筛选区域 -->
            <div class="filter-section">
              <a-space>
                <a-select
                  v-model:value="historyFilter.status"
                  placeholder="全部挂号宠物"
                  style="width: 150px"
                >
                  <a-select-option value="all">全部挂号宠物</a-select-option>
                  <a-select-option value="today">今日挂号</a-select-option>
                  <a-select-option value="week">本周挂号</a-select-option>
                </a-select>

                <a-range-picker
                  v-model:value="historyFilter.dateRange"
                  format="YYYY.MM.DD"
                  @change="onDateRangeChange"
                />

                <a-button @click="setDateRange('today')">今日</a-button>
                <a-button @click="setDateRange('-3')">-3天</a-button>
                <a-button @click="setDateRange('-7')">-7天</a-button>

                <a-input
                  v-model:value="historyFilter.search"
                  placeholder="宠物/电话/医生"
                  style="width: 200px"
                  @keyup.enter="searchHistory"
                >
                  <template #suffix>
                    <a-button type="text" @click="searchHistory">🔍</a-button>
                  </template>
                </a-input>
              </a-space>
            </div>

            <!-- 历史记录表格 -->
            <a-table
              :columns="historyColumns"
              :data-source="filteredHistory"
              :pagination="false"
              size="small"
              row-key="id"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'registrationTime'">
                  {{ record.registrationTime }}
                </template>
                <template v-else-if="column.key === 'registrationFee'">
                  ¥{{ record.registrationFee.toFixed(2) }}
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button
                    type="text"
                    danger
                    size="small"
                    @click="deleteRegistration(record)"
                  >
                    🗑️
                  </a-button>
                </template>
              </template>
            </a-table>
          </a-card>
        </div>
      </div>

      <!-- 右侧：快速操作 -->
      <div class="quick-actions-panel">
        <div class="panel-header">
          <h3>⚡ 快速操作</h3>
        </div>

        <div class="quick-actions">
          <a-button type="primary" block @click="showQuickRegistration">
            🏥 快速挂号
          </a-button>
          <a-button type="primary" block @click="showCustomerSearch">
            👤 查找顾客
          </a-button>
          <a-button type="primary" block @click="showDoctorSchedule">
            📅 医生排班
          </a-button>
          <a-button type="primary" block @click="showStatistics">
            📊 挂号统计
          </a-button>
        </div>

        <div class="statistics">
          <h4>📈 今日统计</h4>
          <div class="stat-item">
            <span>今日挂号:</span>
            <span class="stat-value">{{ todayRegistrations }}</span>
          </div>
          <div class="stat-item">
            <span>待处理:</span>
            <span class="stat-value">{{ pendingRegistrations }}</span>
          </div>
          <div class="stat-item">
            <span>已完成:</span>
            <span class="stat-value">{{ completedRegistrations }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.registration-page {
  height: 100vh;
  background: #f5f5f5;
}

.page-container {
  display: flex;
  gap: 16px;
  height: 100%;
  padding: 16px;
}

.pet-selection-panel {
  display: flex;
  flex-direction: column;
  width: 300px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.registration-content {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 16px;
  overflow-y: auto;
}

.quick-actions-panel {
  display: flex;
  flex-direction: column;
  width: 250px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.search-section {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.pet-list {
  flex: 1;
  padding: 8px;
  overflow-y: auto;
}

.pet-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.3s;
}

.pet-item:hover {
  background: #f5f5f5;
}

.pet-item.active {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
}

.pet-info {
  flex: 1;
}

.pet-name {
  margin-bottom: 4px;
  font-weight: 600;
}

.pet-contact {
  font-size: 12px;
  color: #666;
}

.current-pet-card {
  border-radius: 8px;
}

.pet-details {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.pet-icon {
  margin-top: 8px;
  font-size: 48px;
}

.pet-info-grid {
  display: grid;
  flex: 1;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.info-row {
  display: flex;
  align-items: center;
}

.label {
  width: 80px;
  font-weight: 600;
  color: #666;
}

.value {
  flex: 1;
  color: #262626;
}

.registration-form-card {
  border-radius: 8px;
}

.submit-section {
  padding-top: 16px;
  margin-top: 16px;
  text-align: center;
  border-top: 1px solid #f0f0f0;
}

.history-card {
  border-radius: 8px;
}

.filter-section {
  padding: 16px;
  margin-bottom: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 16px;
}

.statistics {
  padding: 16px;
  margin-top: auto;
  border-top: 1px solid #f0f0f0;
}

.statistics h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
}

.stat-value {
  font-weight: 600;
  color: #1890ff;
}

:deep(.ant-card-head) {
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-card-body) {
  padding: 16px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background: #fafafa;
}
</style>
